package cn.donting.plugin.spring.boot.starter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *
 * @author donting
 *  2020-05-15 上午8:42
 */
@Component
@Slf4j
public final class WebPluginManger extends DefaultPluginManger implements PluginWebManger {
    @Autowired
    RequestPlugId requestPlugId;

    @Override
    public void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String plugId = requestPlugId.getPlugId(request);
        final PluginWrapper pluginWrapper = pluginWrapperHashMap.get(plugId);
        if (plugId == null) {
            log.warn("plugId is null");
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        if (pluginWrapper == null) {
            log.warn("plug not found,request path:" + request.getRequestURI());
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        //设置 线程 ClassLoader  spring中有些资源使用的线程classLoader获取
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(pluginWrapper.getClassLoader());
        PluginDispatcherServlet dispatcherServlet = pluginWrapper.getDispatcherServlet();
        try {
            dispatcherServlet.doService(request, response);
        } catch (Exception e) {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
            throw e;
        }
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}
